#!/usr/bin/python3
# -*- coding:UTF-8 -*-
'''=================================
@Motto : 认真生活,热爱生活
@Name :       Bsea
================================='''
from flask import Blueprint, request, jsonify, session
from api import db
from api.datebase import HomeIndex, AdminMessage, CasualRecordIndex, ImageIndex
import json
ad = Blueprint('admin', __name__, url_prefix='/admin')


# 后台首页数据更新
@ad.route('/updatehomeindex', methods=['PATCH'])
def update_admin_homeindex_message():
    message = request.get_json()
    return message


# 后台首页数据增添
@ad.route('/addhomeindex', methods=['POST'])
def add_admin_homeindex_message():
    messages = request.get_json()
    try:
        message = HomeIndex(CarouselId=messages['message']['CarouselId'],
                            CarouselUrl=messages['message']['CarouselUrl'],
                            CarouselDate=messages['message']['CarouselDate'],
                            LogId=messages['message']['LogId'],
                            LogText=messages['message']['LogText'],
                            LogRemarks=messages['message']['LogRemarks'],
                            LogDate=messages['message']['LogDate'],
                            AboutColor=messages['message']['AboutColor'],
                            AboutIcon=messages['message']['AboutIcon'],
                            AboutTitle=messages['message']['AboutTitle'],
                            AboutText=messages['message']['AboutText'])
        print(messages['message']['LogRemarks'])
        db.session.add(message)
        db.session.commit()
        return jsonify({'code': '200', 'msg': '增添成功!'})
    except:
        return jsonify({"code": "301", "date": "添加失败"})


# 后台首页数据删除
@ad.route('/deletehomeindex', methods=['POST'])
def delete_admin_homeindex_message():
    messages = request.get_json()
    if messages['id'] == "1":
        Get_CarouselId = messages['CarouselId']
        note1 = HomeIndex.query.filter_by(CarouselId=Get_CarouselId)
        for i in note1:
            db.session.delete(i)
            db.session.commit()
    if messages['id'] == "2":
        Get_LogId = messages['LogId']
        note2 = HomeIndex.query.filter_by(LogId=Get_LogId)
        for m in note2:
            db.session.delete(m)
            db.session.commit()
    if messages['id'] == "3":
        Get_AboutTitle = messages['AboutTitle']
        note3 = HomeIndex.query.filter_by(AboutTitle=Get_AboutTitle)
        for n in note3:
            db.session.delete(n)
            db.session.commit()
    return jsonify({'code': '200', 'msg': '删除成功!'})


# admin退出登陆
@ad.route('/logout', methods=["GET"])
def admin_logout():
    try:
        if session['username'] is not None:
            session.clear()
            return jsonify({"code": "600", "msg": "退出成功!"})
    except:
        return jsonify({"code": "601", "msg": "退出失败!"})


# 后台个人中心展示
@ad.route('/getuser', methods=['POST'])
def get_admin_user_message():
    try:
        get_message = request.get_json()
        get_username = get_message['username']
        message = AdminMessage.query.filter_by(username=get_username).first()
        return jsonify({'code': '200',
                        'msg': {'name': message.name, 'age': message.age, 'phone': message.phone, 'mall': message.mall,
                                'wechat': message.wechat, 'qq': message.qq}})
    except:
        return jsonify({'code': '201',
                        'msg': '查询失败!'})


# 首页数据获取
def admin_homeindex_message(messages):
    return {
        'id': messages.id,
        'CarouselId': messages.CarouselId,
        'CarouselUrl': messages.CarouselUrl,
        'CarouselDate': messages.CarouselDate,
        'LogId': messages.LogId,
        'LogText': messages.LogText,
        'LogRemarks': messages.LogRemarks,
        'LogDate': messages.LogDate,
        'AboutColor': messages.AboutColor,
        'AboutIcon': messages.AboutIcon,
        'AboutTitle': messages.AboutTitle,
        'AboutText': messages.AboutText,
    }


@ad.route('/gethomeindex', methods=['GET'])
def get_admin_homeindex_message():
    try:
        message = HomeIndex.query.all()
        messages = json.dumps(message, default=admin_homeindex_message)
        return jsonify({"code": "200", "date": messages})
    except:
        return jsonify({"code": "201", "date": "获取失败"})


# admin登陆
@ad.route('/login', methods=["POST"])
def admin_login():
    message = request.get_json()
    username = message.get("username")
    password = message.get("password")
    if not all([username, password]):
        return jsonify({'code': "401", 'msg': '参数不全!'})
    try:
        admin_user = AdminMessage.query.filter_by(username=username).first()
        if admin_user and admin_user.password == password:
            session["username"] = username
            return jsonify({'code': "200", 'msg': '登录成功!', 'username': admin_user.username})
        else:
            return jsonify({'code': "201", 'msg': '账号或密码错误!'})
    except:
        return jsonify({'code': "202", 'msg': '登录失败!'})


# # admin检查登陆
# @ad.route('/checklogin', methods=["GET"])
# def admin_checklogin():
#     try:
#         username = session['username']
#         if username is not None:
#             return jsonify({"code": "500", "msg": {"username": username}})
#     except:
#         return jsonify({"code": "501", "msg": "你还未登陆!"})


# 随记管理
# 获取数据
def getCasualRecordpage(message):
    return {
        'id': message.id,
        'reveal': message.reveal,
        'updateContext': message.updateContext,
        'ArticleId': message.CasualRecordId,
        'ArticleTitle': message.Title,
        'ArticleDate': message.Date,
        'ArticleUrl': message.ImgUrl,
        'ArticleIntroduction': message.Introduction,
        'ArticleContext': message.Context,
    }


@ad.route('/getcasualrecordpage', methods=['GET'])
def get_casualrecord_page():
    try:
        get_message = CasualRecordIndex.query.all()
        message = json.dumps(get_message, default=getCasualRecordpage)
        return jsonify({'code': '200', 'msg': message})
    except:
        return jsonify({'code': '201', 'msg': '获取失败!'})


# 删除图片
@ad.route('/deletecasualrecord', methods=['POST'])
def delete_casual_record():
    get_index = request.get_json()
    casualrecord_id = get_index.get('id')
    message = CasualRecordIndex.query.filter_by(id=casualrecord_id)
    for i in message:
        db.session.delete(i)
        db.session.commit()
    return jsonify({"code": "200", 'msg': casualrecord_id})


# 添加图片
@ad.route('/addcasualrecord', methods=['POST'])
def add_casualrecord():
    try:
        get_message = request.get_json()
        message = CasualRecordIndex(
            Context=get_message['message']['ArticleContext'],
            CasualRecordId=get_message['message']['ArticleId'],
            Introduction=get_message['message']['ArticleIntroduction'],
            Title=get_message['message']['ArticleTitle'],
            Date=get_message['message']['ArticleDate'],
            ImgUrl=get_message['message']['ArticleUrl'])
        db.session.add(message)
        db.session.commit()
        return jsonify({'code': '200', 'msg': '增添成功!'})
    except:
        return jsonify({'code': '201', 'msg': '增添失败!'})


# 管理页图片管理
# 获取数据
def getimgpage(message):
    return {
        'id': message.id,
        'imgId': message.imgId,
        'imgUrl': message.imgUrl,
        'imgDate': message.imgDate,
        'imgTitle': message.imgTitle,
        'imgRemarks': message.imgRemarks,
    }


@ad.route('/getimgpage', methods=['GET'])
def get_img_page():
    try:
        get_message = ImageIndex.query.all()
        message = json.dumps(get_message, default=getimgpage)
        return jsonify({'code': '200', 'msg': message})
    except:
        return jsonify({'code': '201', 'msg': '获取失败!'})


# 删除图片
@ad.route('/deleteimg', methods=['POST'])
def delete_img():
    get_index = request.get_json()
    img_id = get_index.get('id')
    print(img_id, get_index)
    message = ImageIndex.query.filter_by(id=img_id)
    for i in message:
        db.session.delete(i)
        db.session.commit()
    return "ok"


# 添加图片
@ad.route('/addimg', methods=['POST'])
def add_img():
    try:
        get_message = request.get_json()
        message = ImageIndex(imgUrl=get_message['message']['imgUrl'],
                             imgId=get_message['message']['imgId'],
                             imgRemarks=get_message['message']['imgRemarks'],
                             imgTitle=get_message['message']['imgTitle'],
                             imgDate=get_message['message']['imgDate'])
        db.session.add(message)
        db.session.commit()
        return jsonify({'code': '200', 'msg': '增添成功!'})
    except:
        return jsonify({'code': '201', 'msg': '增添失败!'})
